package csc.fresher.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.fresher.dao.UserDAOImpl;
import csc.fresher.domain.User;

/**
 * Servlet implementation class LoginServlet
 */

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Date date = new Date();
	static {
		User admin = new User();
		admin.setUsername("admin");
		admin.setPassword("admin123");
		admin.setAdmin(true);
		admin.setRegisterDate(date);
		UserDAOImpl.listUser.add(admin);

		User user01 = new User();
		user01.setUsername("user01");
		user01.setPassword("P@ssword123");
		user01.setAdmin(false);
		user01.setRegisterDate(date);
		UserDAOImpl.listUser.add(user01);

		User user02 = new User();
		user02.setUsername("user02");
		user02.setPassword("P@ssword123");
		user02.setAdmin(false);
		user02.setRegisterDate(date);
		UserDAOImpl.listUser.add(user02);

		User user03 = new User();
		user03.setUsername("user03");
		user03.setPassword("P@ssword123");
		user03.setAdmin(false);
		user03.setRegisterDate(date);
		UserDAOImpl.listUser.add(user03);
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("inputName");
		String password = request.getParameter("inputPassword");
		UserDAOImpl dao = new UserDAOImpl();
		if (dao.checkUser(username)) {
			User user = dao.getUser(username);
			if (user.getPassword().equals(password)) {
				HttpSession session = request.getSession();
				session.setAttribute("username", user.getUsername());
				request.setAttribute("messageLoginSuccess",
						"Congratulation ! You login success");
				request.getRequestDispatcher("index.jsp").forward(
						request, response);
			} else {
				request.setAttribute("messageLogin",
						"Wrong username or password");
				request.getRequestDispatcher("login.jsp").forward(request,
						response);
			}
		} else {
			request.setAttribute("messageLogin",
					"Wrong username or password");
			request.getRequestDispatcher("login.jsp").forward(request,
					response);
		}
	}

}
